﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using ProjectEuler.Linq;

namespace ProjectEuler.Problems
{
    [EulerProblem(26, 983)]
    [Description("Find the value of d < 1000 for which 1/d contains the longest recurring cycle.")]
    internal sealed class Problem026 : EulerProblem
    {
        public override Object Solve()
        {
            return (2).To(999).WithMax(d => GetRecurringCycleLength(d));
        }

        private static Int32 GetRecurringCycleLength(Int32 d)
        {
            var remainders = new List<Int32>();
            var rem = 10;

            while (rem > 0)
            {
                while (rem < d)
                {
                    rem *= 10;
                }

                Math.DivRem(rem, d, out rem);

                if (rem > 0)
                {
                    var index = remainders.IndexOf(rem);

                    if (index > -1)
                    {
                        return remainders.Count - index;
                    }

                    remainders.Add(rem);
                }
            }

            return 0;
        }
    }
}
